import { ref } from 'vue';
import { Modal } from '@jecloud/ui';
import ListenerEditor from '@/components/listener-editor/index.vue';

/**
 *
 * @param {Object} options
 * @param {String} funcId 功能Id
 * @param {String} funcName 功能名称
 * @param {String} funcCode 功能编码
 * @param {String} onId 业务数据Id
 * @param {String} eventType 类型
 * @param {String} title 标题
 * * @param {String} eventInfo 回显的数据
 * @param {Function} callback 回调函数
 *
 */

export function listenerEditorModal(options) {
  const {
    funcId,
    defaultCode,
    funcName,
    funcCode,
    onId,
    eventType,
    fieldType,
    title,
    eventInfo,
    callback,
  } = options;
  const recordData = {
    id: funcId,
    text: funcName,
    code: funcCode,
    onId,
    eventType: eventType ? eventType : 'default',
    eventInfo,
    fieldType: fieldType ? fieldType : '',
    title: title ? title : '脚本编辑器（Ctrl+S保存）',
    defaultCode: defaultCode ?? '',
  };
  const listenerEditorRef = ref();
  const dataRef = ref(recordData);
  let modalEle = ref(null); // 窗口对象
  const width = document.documentElement.clientWidth - 100;
  // 确认操作
  const okButton = function (data) {
    callback?.(data);
  };

  // 初始选中值
  const onShow = function ({ $modal }) {
    modalEle.value = $modal;
  };

  const listenerEditor = () => {
    return (
      <ListenerEditor
        ref={listenerEditorRef}
        recordData={dataRef.value}
        bodyBorder
        modalEle={modalEle.value}
        allowDeselect={false}
        onCellDblclick={okButton}
      />
    );
  };

  return Modal.window({
    title: dataRef.value.title,
    maximizable: true,
    width,
    bodyStyle: { padding: '0 20px' },
    height: document.documentElement.clientHeight - 50,
    headerStyle: { height: '60px' },
    onShow,
    className: 'listener-modal',
    slots: {
      default: listenerEditor,
    },
    onClose: () => {
      let md = document.querySelector('.listener-modal  .tool--close');
      md && md.removeEventListener('click', listenerEditorRef.value.handlerBbar);
    },
  });
}
